#!/usr/bin/python
import sys
from itertools import combinations

#	agglomeration of faults int central entities
class FaultsAnalyzer:

	def __init__(self , conf , data):
		self.conf 	= conf
		self.data 	= data
		self.faults_min = 2 if not "faults_min" in self.conf else self.conf['faults_min']
		self.alertdata 	= {}
		#	How many parts all keys have
		self.key_parts	= len(data.keys()[0].split(conf['splitter'])) if len(data.keys()) > 0 else 0

	def do_process(self):
		for num in range(self.key_parts  , 0 , -1):
			self.break_into(num)	

	
	def break_into(self , num):
		self.alertdata[num] = {}
		for k1 in self.data :
			#	k2 holds all combinations of key list
			for k2 in  combinations(k1.split(self.conf['splitter']) , num) : 
				#	k3 LIKE each in 'a^^^b^^^c' => 'a^^^b' , 'a^^^c'  , 'b^^^c'
				k3 = self.conf['splitter'].join(k2)
				self.row_merge(k3 , self.alertdata[num] , self.data[k1])
		self.do_faults_min( num )


	def do_faults_min(self , num ):
		factor = (self.key_parts - num ) * self.faults_min
		localdata = {}
		for k in  self.alertdata[num] :
			localdata[k] = {}
			for f in self.alertdata[num][k] :										
				if self.alertdata[num][k][f] >= factor : 
					localdata[k][f] = self.alertdata[num][k][f] 
			if len(localdata[k].keys()) == 0 : del localdata[k]
		self.alertdata[num] = localdata
				

	def row_merge(self , k , buff , rowdata):
		#	SUM values :  {"A":1,"B":2} , {"A":1 , "C":2}	=>  {"A":2 , "B":2 , "C":2}
		if k not in buff : buff[k] = {}
		for f in rowdata:
			buff[k][f] =  rowdata[f] if not f in buff[k] else buff[k][f] + rowdata[f]


